import { _decorator } from "cc";
import { eventDispatcher } from "../Constants";
import { Entity, IEntity } from "./Entity";
import { AnimatorParam } from "../enums/AnimatorParam";
import { EventType } from "../enums/EventType";
import { DataManager } from "../manager/DataManager";
const { ccclass } = _decorator;

export interface ISpikes extends IEntity {
    count: number
}

@ccclass("Spikes")
export class Spikes extends Entity {

    private _totalCount: number = 0;
    private _count: number = 0;

    public get totalCount(): number {
        return this._totalCount;
    }

    public get count(): number {
        return this._count;
    }

    public getData(): ISpikes {
        return {
            x: this.x,
            y: this.y,
            state: this.state,
            direction: this._direction,
            type: this._type,
            count: this._count,
            id: this.id
        }
    }

    public setData(value: ISpikes): void {
        super.setData(value);
        this._count = value.count;
    }

    public init(param: ISpikes): void {
        this._totalCount = param.count;
        super.init(param);
    }

    protected registerEvents(): void {
        eventDispatcher.on(EventType.PLAYER_MOVE_END, this.onPlayerMove, this);
    }

    private onPlayerMove(x: number, y: number, lastX: number, lastY: number): void {
        this._count = (this._count + 1) % (this._totalCount + 2);
        if (x === this.x && y === this.y && this._count === this._totalCount + 1) {
            eventDispatcher.emit(EventType.ATTACK_PLAYER);
        }
        this._animationController.setValue(AnimatorParam.STEP, true);
    }

    public onTickComplete(): void {
        if (this._count === this._totalCount + 1) {
            this._count = 0;
            this._animationController.setValue(AnimatorParam.STEP, true);
        }
    }
}